import axios from "axios";
import {useEffect, useState} from "react";
import {message} from "antd";

interface GiveALike {
    articleId: number,
    userId: number
}

interface Article {
    id: number,
    content: string,
    isLike?: number
}

const Home = () => {
    const [articleList, setArticleList] = useState<Article[]>([]);
    //点赞所需的参数
    const [giveALike] = useState<GiveALike>({
        articleId: 0,//文章编号
        userId: 0//用户编号
    });

    //获取所有内容
    const getList = async () => {
        const response = await axios.get("http://localhost:5000/giveALike/getList")
        setArticleList(response.data)
    }

    //点赞
    const handleLike = (row: number) => {
        //从session中获取用户信息
        const user = JSON.parse(window.sessionStorage.getItem("user") || '')
        //设置用户编号
        giveALike.userId = user.id
        //设置文章编号
        giveALike.articleId = row
        axios.post("http://localhost:5000/giveALike/saveUserLike", giveALike).then((res) => {
            getList()
            if (res.data.isLike == 1) {
                message.success('点赞成功');
            } else {
                message.warning('取消点赞');
            }
        })
    }

    //vite方式获取图片
    const getImageUrl = (name: string) => {
        return new URL(`../assets/${name}`, import.meta.url).href
    }

    useEffect(() => {
        getList()
    }, []);

    return (
        <>
            <div>
                {articleList.map((item: Article) => (
                    <div key={item.id} style={{display: "flex", fontSize: "30px"}}>
                        <div style={{marginRight: "10px"}}>编号:{item.id}</div>
                        <div style={{marginRight: "10px"}}>内容:{item.content}</div>
                        {
                            item.isLike == 0
                                ?
                                <img onClick={() => {
                                    handleLike(item.id)
                                }} src={getImageUrl("未点赞.png")}
                                     style={{width: "50px", height: "50px", cursor: "pointer"}} alt="图片"/>
                                :
                                <img onClick={() => {
                                    handleLike(item.id)
                                }} src={getImageUrl("点赞.png")}
                                     style={{width: "50px", height: "50px", cursor: "pointer"}} alt="图片"/>
                        }

                    </div>
                ))}
            </div>
        </>
    );
}

export default Home;